﻿using Microsoft.Extensions.DependencyInjection;
using WebApiClientCore.Extensions.OAuths;
using WebApiClientCore.Extensions.OAuths.TokenProviders;

namespace HuanTian.WebCore
{
    public static class WebApiClientExtensions
    {
        /// <summary>
        /// 中间件 WebApiClient 注入拓展
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddWebApiClientService(this IServiceCollection services)
        {
            services.AddHttpApi<ITestThreeService>().ConfigureHttpApi(o =>
            {
                //o.UseLogging = Environment.();
                //o.HttpHost = new Uri("http://localhost:8080/");

                // o.JsonSerializeOptions -> json 序列化选项
                // o.JsonDeserializeOptions -> json 反序列化选项
                // o.KeyValueSerializeOptions -> 键值对序列化选项
                // o.XmlSerializeOptions -> xml 序列化选项
                // o.XmlDeserializeOptions -> xml 反序列化选项
                // o.GlobalFilters -> 全局过滤器集合
            });
            // 注入 TokenProvider
            services.AddTokenProvider<ITestThreeService, WebApiClientTokenProvider>();
            return services;
        }
    }
    /// <summary>
    /// WebApiClient 自动获取Token配置
    /// </summary>
    public class WebApiClientTokenProvider : TokenProvider
    {
        public WebApiClientTokenProvider(IServiceProvider serviceProvider)
            : base(serviceProvider)
        {

        }
        /// <summary>
        /// 获取token
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        protected override async Task<TokenResult?> RequestTokenAsync(IServiceProvider serviceProvider)
        {
            var loginInput = new TestLoginInput
            {
                UserName = "test-admin",
                Password = "123456"
            };
            if (string.IsNullOrEmpty(loginInput.UserName) || string.IsNullOrEmpty(loginInput.Password))
                throw new Exception("第三方接口,未填写鉴权用户信息,请修改后再试。");
            var loginInfo = await serviceProvider.GetRequiredService<ITestThreeService>()
                                               .Login(loginInput);
            var tokenResult = new TokenResult
            {
                Access_token = loginInfo.Data?.ToString() ?? ""
            };
            return tokenResult;
        }
        /// <summary>
        /// 刷新token
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="refresh_token"></param>
        /// <returns></returns>
        protected override Task<TokenResult?> RefreshTokenAsync(IServiceProvider serviceProvider, string refresh_token)
        {
            return this.RequestTokenAsync(serviceProvider);
        }
    }
}
